﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace EmaMetadata
{
    public static class XmlExtensions
    {

        #region Extension methods to simplify XML loading and saving
        /// <summary>
        /// Retrieve a specified attribute, or a null value if not present
        /// </summary>
        /// <param name="n"></param>
        /// <param name="attr_name"></param>
        /// <returns></returns>
        public static string ValueOrDefault(this XmlNode n, string attr_name)
        {
            if (n != null) {
                if (n.Attributes != null) {

                    // Try once with the name properly spelled
                    XmlAttribute a = n.Attributes[attr_name];
                    if (a != null) {
                        return a.Value;
                    }

                    // Try again with all lowercase
                    a = n.Attributes[attr_name.ToLower()];
                    if (a != null) {
                        return a.Value;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// Retrieve a specified attribute as an int, or zero if it doesn't exist or if it fails to parse
        /// </summary>
        /// <param name="n"></param>
        /// <param name="attr_name"></param>
        /// <returns></returns>
        public static int ValueOrDefaultInt(this XmlNode n, string attr_name)
        {
            int i;
            if (int.TryParse(ValueOrDefault(n, attr_name), out i)) {
                return i;
            }
            return 0;
        }

        /// <summary>
        /// Retrieve a specified attribute as a nullable datetime, or null if it doesn't exist or fails parsing
        /// </summary>
        /// <param name="n"></param>
        /// <param name="attr_name"></param>
        /// <returns></returns>
        public static Nullable<DateTime> ValueOrDefaultDateTime(this XmlNode n, string attr_name)
        {
            DateTime dt;
            if (DateTime.TryParse(ValueOrDefault(n, attr_name), out dt)) {
                return dt;
            }
            return null;
        }
        #endregion
    }
}
